package com.rzico.sbl.ui.statistic

import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.core.widget.doOnTextChanged
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityBucketBackBinding
import com.rzico.sbl.model.HandleData
import com.rzico.sbl.other.getBeforeDate
import com.rzico.sbl.other.getBeforeEndDate
import com.rzico.sbl.other.getBeforeFirstDate
import com.rzico.sbl.other.getEndDate
import com.rzico.sbl.other.getFirstDate
import com.rzico.sbl.other.getMondayDate
import com.rzico.sbl.other.getSundayDate
import com.rzico.sbl.other.getTodayDate
import com.rzico.sbl.other.getYearEndDate
import com.rzico.sbl.other.getYearFirstDate
import com.rzico.sbl.other.userRole
import com.rzico.sbl.ui.member.MemberDetailActivity
import com.rzico.sbl.viewmodel.StatisticCommonViewModel
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.extend.condition
import com.xinnuo.common.extend.conditionFalse
import com.xinnuo.common.extend.formatDecimal
import com.xinnuo.common.extend.get
import com.xinnuo.common.extend.getExtra
import com.xinnuo.common.extend.gone
import com.xinnuo.common.extend.notEmpty
import com.xinnuo.common.extend.oneClick
import com.xinnuo.common.extend.optNotEmpty
import com.xinnuo.common.extend.optNotNull
import com.xinnuo.common.extend.startActivityEx
import com.xinnuo.common.extend.textTrim
import com.xinnuo.common.helper.hideSoftInput
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.count
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.glideExt.loadCircleImage
import com.xinnuo.common_ui.utils.showTimeRangeDialog
import com.xinnuo.slimadapter.SlimAdapter
import org.json.JSONObject

class BucketBackActivity : BaseActivity(R.layout.activity_bucket_back) {

    private val mBinding by lazy { ActivityBucketBackBinding.bind(getRootView()) }

    private var mKeyWord = ""
    private lateinit var mDateMode: String
    private lateinit var mBeginDate: String
    private lateinit var mEndDate: String

    override fun getViewModel() = get<StatisticCommonViewModel>()

    override fun initData() {
        setToolbarVisibility(false)

        initLayout()
        initSearch()

        mBinding.apply {
            mKeyWord.notEmpty {
                backSearch
                    .searchEdit
                    .apply {
                        setText(this@notEmpty)
                        setSelection(text.length)
                    }
            }

            listLayout
                .swipeRefresh
                .isRefreshing = true
        }

        getData(pageNum)
    }

    private fun initLayout() {
        mBinding.listLayout.apply {
            emptyLayout.also {
                it.emptyHint.text = "暂无相关退桶记录！"
            }

            recycleList.also { view ->
                view.loadLinear(
                    refresh = swipeRefresh,
                    onRefresh = { getData(0) },
                    onLoad = {
                        isLoadingMore
                            .conditionFalse {
                                isLoadingMore = true
                                getData(pageNum)
                            }
                    }
                )

                view.addItemDecoration(SpaceTBDecoration(hasHeader = false))

                mAdapter = SlimAdapter.creator()
                    .register<HandleData>(R.layout.item_statistic_handle_back) { jector, bean, _ ->
                        jector.apply {
                            text(R.id.item_back_title, bean.name)
                            text(R.id.item_back_name, bean.consignee)
                            text(R.id.item_back_phone, bean.phone)
                            text(R.id.item_back_count, bean.subQuantity)
                            text(R.id.item_back_price, bean.subPrice.formatDecimal())

                            with<ImageView>(R.id.item_back_img) {
                                it.loadCircleImage(bean.memberLogo, R.mipmap.default_user)
                            }

                            clicked(R.id.item_back_img) {
                                (userRole in "1,2")
                                    .condition {
                                        startActivityEx<MemberDetailActivity>(
                                            "cardId" to bean.cardId,
                                            "memberId" to bean.memberId
                                        )
                                    }
                            }
                        }
                    }
                    .attachTo(view)
            }
        }
    }

    private fun initSearch() {
        mBinding
            .backSearch
            .apply {
                searchEdit.hint = "请输入姓名、手机号"
                searchEdit.doOnTextChanged { text, _, _, _ ->
                    text?.let {
                        searchClose.isGone = it.isEmpty()

                        if (it.isEmpty() && mKeyWord.isNotEmpty()) {
                            mKeyWord = ""
                            updateList()
                        }
                    }
                }

                searchEdit.setOnEditorActionListener { _, actionId, _ ->
                    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                        hideSoftInput() //隐藏软键盘

                        if (searchEdit.text.isBlank()) {
                            showToast("请输入姓名、手机号")
                        } else {
                            mKeyWord = searchEdit.textTrim
                            updateList()
                        }
                    }
                    return@setOnEditorActionListener false
                }

                searchClose.oneClick { searchEdit.setText("") }
                searchHint.oneClick {
                    if (searchEdit.text.isBlank()) {
                        showToast("请输入姓名、手机号")
                    } else {
                        mKeyWord = searchEdit.textTrim
                        updateList()
                    }
                }
            }
    }

    override fun initListener() {
        mKeyWord = intent.getExtra("keyword")
        mDateMode = intent.getExtra("dateMode")
        mBeginDate = intent.getExtra("beginDate")
        mEndDate = intent.getExtra("endDate")

        mBinding.apply {
            // 今日、昨日、本周、本月、上月、本年、自定义
            when (mDateMode) {
                "1" -> {
                    backTime.timeHint.text = "今日"
                    getViewModel().mUncheckTimeList[0].isChecked = true
                }

                "2" -> {
                    backTime.timeHint.text = "昨日"
                    getViewModel().mUncheckTimeList[1].isChecked = true
                }

                "3" -> {
                    backTime.timeHint.text = "本周"
                    getViewModel().mUncheckTimeList[2].isChecked = true
                }

                "5" -> {
                    backTime.timeHint.text = "上月"
                    getViewModel().mUncheckTimeList[4].isChecked = true
                }

                "6" -> {
                    backTime.timeHint.text = "本年"
                    getViewModel().mUncheckTimeList[5].isChecked = true
                }

                "7" -> {
                    backTime.timeHint.text = "$mBeginDate ~ $mEndDate"
                    getViewModel().mUncheckTimeList[6].isChecked = true
                }

                else -> {
                    mBeginDate = getFirstDate()
                    mEndDate = getEndDate()

                    backTime.timeHint.text = "本月"
                    getViewModel().mUncheckTimeList[3].isChecked = true
                }
            }
        }

        mBinding
            .backTime
            .apply {
                timeLayout.oneClick {
                    getViewModel()
                        .showDropTimeFilter(
                            getIContext(),
                            timeHint,
                            timeHintArrow,
                            timeLayout,
                            getViewModel().mUncheckTimeList
                        ) { bean ->

                            if (bean.id != "7")
                                getViewModel()
                                    .mUncheckTimeList
                                    .last()
                                    .name = "自定义时间"

                            when (bean.id) {
                                "1" -> {
                                    mBeginDate = getTodayDate()
                                    mEndDate = getTodayDate()

                                    updateList()
                                }

                                "2" -> {
                                    mBeginDate = getBeforeDate()
                                    mEndDate = getBeforeDate()

                                    updateList()
                                }

                                "3" -> {
                                    mBeginDate = getMondayDate()
                                    mEndDate = getSundayDate()

                                    updateList()
                                }

                                "4" -> {
                                    mBeginDate = getFirstDate()
                                    mEndDate = getEndDate()

                                    updateList()
                                }

                                "5" -> {
                                    mBeginDate = getBeforeFirstDate()
                                    mEndDate = getBeforeEndDate()

                                    updateList()
                                }

                                "6" -> {
                                    mBeginDate = getYearFirstDate()
                                    mEndDate = getYearEndDate()

                                    updateList()
                                }

                                "7" -> {
                                    showTimeRangeDialog(
                                        isCurrentDate = true,
                                        isAfterLimited = true,
                                        onResult = { start, end ->
                                            getViewModel()
                                                .mUncheckTimeList
                                                .forEach { it.isChecked = false }

                                            getViewModel()
                                                .mUncheckTimeList
                                                .last()
                                                .isChecked = true

                                            mBeginDate = start
                                            mEndDate = end
                                            bean.name = "$mBeginDate ~ $mEndDate"
                                            timeHint.text = bean.name

                                            updateList()
                                        }
                                    )
                                }
                            }
                        }
                }
            }

        getViewModel()
            .mBackEvent
            .observe(this) {
                val obj = JSONObject(it).optJSONObject("data") ?: JSONObject()

                mBinding.apply {
                    backCount.text = obj.optNotEmpty("subQuantity", "0")
                    backMoney.text = obj.optNotNull("subPrice").formatDecimal()
                }
            }
    }

    /**
     * 押桶记录列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        // 押桶记录合计
        getViewModel()
            .backTotal(
                keyWord = mKeyWord,
                barrelId = intent.getExtra("barrelId"),
                beginDate = mBeginDate,
                endDate = mEndDate
            )

        // 押桶记录列表
        getViewModel()
            .backRecord(
                page = index,
                keyWord = mKeyWord,
                barrelId = intent.getExtra("barrelId"),
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = {
                    mList.apply {
                        if (index == 0) {
                            clear()
                            pageNum = 0
                        }
                        addItems(it)
                        if (it.count() > 0) pageNum++
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

}